package com.qdu.controller;

import com.qdu.entity.Houseinfo;
import com.qdu.service.HouseService;
import com.qdu.util.GenerateUUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class testController {

    @Autowired
    HouseService houseService;

    @PostMapping("/addHouse")
//    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
//    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    public Result addHouse(Houseinfo houseinfo, List<MultipartFile> files, HttpServletRequest req){
//        System.out.println("进入add方法");
        Result result=new Result();
        System.out.println(houseinfo);
        for(MultipartFile file : files){
            System.out.println(file.getOriginalFilename());
        }
        String url="";
//        String filePath = "";
//        System.out.println(record);
//        System.out.println(files[0].getOriginalFilename());
        for (MultipartFile file : files){
            System.out.println(file.getOriginalFilename());
            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            String originName = file.getOriginalFilename();
            System.out.println(originName);

            String format = sdf.format(new Date());

            String realPath = req.getServletContext().getRealPath("/") + format;
            System.out.println(realPath);

            File folder = new File(realPath);
            if(!folder.exists()){
                folder.mkdirs();
            }
            String newName = UUID.randomUUID().toString() + ".jpg";
            try {
                file.transferTo(new File(folder, newName));
                url =url+req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName+"|";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        houseinfo.setHid("H" + GenerateUUID.generateUUID());
        houseinfo.setHimg(url);
        houseinfo.setHreleasedate(new Date());
        houseinfo.setTag("tag");
        houseinfo.setLoaction("location");
        houseinfo.setGoodhouse(false);
        houseService.insert(houseinfo);
        System.out.println(url);
        System.out.println(houseinfo);

        result.setStatus(true);
        result.setMsg("房屋信息发布成功，正在等待管理员审核！");

        return result;
    }

}
